package com.example.myapplication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import androidx.cardview.widget.CardView;

import java.util.List;

public class CardAdapter extends BaseAdapter {
    private List<Card> cards;
    private LayoutInflater inflater;

    public CardAdapter(List<Card> cards, LayoutInflater inflater) {
        this.cards = cards;
        this.inflater = inflater;
    }

    @Override
    public int getCount() {
        return cards.size();
    }

    @Override
    public Object getItem(int position) {
        return cards.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_card, parent, false);
            holder = new ViewHolder();
            holder.cardView = convertView.findViewById(R.id.cardView);
            holder.tvCardBack = convertView.findViewById(R.id.tvCardBack);
            holder.tvCardFront = convertView.findViewById(R.id.tvCardFront);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        
        Card card = cards.get(position);
        
        if (card.isMatched()) {
            // 已匹配的卡片显示绿色背景
            holder.cardView.setCardBackgroundColor(convertView.getContext().getColor(R.color.card_matched));
            holder.tvCardBack.setVisibility(View.GONE);
            holder.tvCardFront.setVisibility(View.VISIBLE);
            holder.tvCardFront.setText(String.valueOf(card.getValue()));
        } else if (card.isFaceUp()) {
            // 正面朝上的卡片
            holder.cardView.setCardBackgroundColor(convertView.getContext().getColor(R.color.card_front));
            holder.tvCardBack.setVisibility(View.GONE);
            holder.tvCardFront.setVisibility(View.VISIBLE);
            holder.tvCardFront.setText(String.valueOf(card.getValue()));
        } else {
            // 背面朝上的卡片
            holder.cardView.setCardBackgroundColor(convertView.getContext().getColor(R.color.card_back));
            holder.tvCardBack.setVisibility(View.VISIBLE);
            holder.tvCardFront.setVisibility(View.GONE);
        }
        
        return convertView;
    }
    
    private static class ViewHolder {
        CardView cardView;
        TextView tvCardBack;
        TextView tvCardFront;
    }
    
    public void updateCards(List<Card> cards) {
        this.cards = cards;
        notifyDataSetChanged();
    }
}